package com.company;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @date : 2022/6/30 16:30
 * HashMap线程不安全验证：jdk1.8会造成数据丢失
 */

public class P019_HashMapThreadUnsafe {

    public static void main(String[] args) {

        Map<Integer, Integer> map = new HashMap<>();
        // 线程安全的类
//        Map<Integer, Integer> map = new ConcurrentHashMap<>();
        int count = 1000;
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            int a = i;
            new Thread(() -> {
                map.put(a, a);
                latch.countDown();
            }).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        for (int i = 0; i < count; i++) {
            if (map.get(i) == null) {
//                System.out.println("i = " + i);
                num1++;
            } else if (map.get(i) == i) {
                // key == value
                num2++;
            } else {
                // key!=value 没有这种可能
                num3++;
            }
        }
        System.out.println(num1 + "+" + num2 + "+" + num3 + "=" + count);
        // map 实际元素个数和 map.size() 不一致，也是HashMap多线程引发的问题
        System.out.println(map.size());
    }

}
